package main

import (
	"fmt"
	"math"
)

func main() {
	nums := []int{1,3}
	fmt.Println(searchInsert(nums, 1))
}

func searchInsert(nums []int, target int) int {
	if len(nums) == 1 {
		if nums[0] == target {
			return 0
		} else if nums[0] > target {
			return 0
		} else if nums[0] < target {
			return 1
		}
	}
	ps, pe := 0, len(nums)-1
	for pe-ps > 1 {
		t := int(math.Floor(float64(ps+pe) / float64(2)))
		if target > nums[t] {
			ps = t
		} else if target < nums[t] {
			pe = t
		} else {
			return t
		}
	}

	if target > nums[pe] {
		return pe + 1
	}

	if target <= nums[ps] {
		return ps
	}

	if target > nums[ps] {
		return ps + 1
	}

	return -1
}
